package com.gaoyang.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gaoyang.domain.Product1;
import com.gaoyang.domain.Product2;
import com.gaoyang.service.ProductService;
import com.gaoyang.util.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

@Component
public class ScheduledTasks4Zhaoshang {

    private Logger logger = LogManager.getLogger(ScheduledTasks4Zhaoshang.class);

    @Autowired
    ProductService productService;

    @Scheduled(fixedRate = 60000)
    public void getProductList() throws Exception{
        Vector productList = new Vector();
        String productUrl = API_URL.ZSYH_ADDRESS2 + API_URL.ZSYH.PRODUCT_9POINT_LIST_URL2;
        Map params = new HashMap();
        params.put("p1", "35");
        params.put("body", "{\"cityNo\":\"10\",\"regionId\":\"\",\"longitude\":\"116.4505579326416\",\"labelId\":\"01\",\"dimension\":\"39.93005504289196\",\"merTypeId2\":\"\",\"signOfOrder\":\"1\",\"districtId\":\"\"}");
        params.put("p6", "478931494");
        params.put("p2", "68281119-1AB4-4D63-A54C-B9F499902DF3");
        params.put("p7", "C7C5BC31E5544437BE1D43CF7F735627");
        params.put("p3", "22FCB3CBBC534C61B4775AD4740DB4E7f");
        params.put("p8", "10B9D155-E63B-4ABC-8956-769CC0D0F561");
        params.put("p4", "A83D0972-344A-4724-974B-9F059BA93BC1");
        params.put("p9", "7a33ae01d478482c81f9003277f7c90e");
        params.put("p0", "i");
        params.put("p10", "BE17D154-DD6A-4FB9-975D-00B601AD0D3E");
        params.put("p5", "17A8AF7157CD46FBAC97188626CA08A0");
        params.put("syshead", "{\"pageSize\":10,\"trans_code\":\"SI_PRD0010\",\"chn1_id\":\"01\",\"sessionId\":\"7a33ae01d478482c81f9003277f7c90e\",\"session_id\":\"123124123\",\"user_id\":\"17A8AF7157CD46FBAC97188626CA08A0\",\"pageIndex\": 1}");
        String result = HttpUtils4Black.postUrl4ZSYH(productUrl, params);
        JSONObject obj = JSONObject.parseObject(result);
        JSONObject bodyObj = (JSONObject) obj.get("body");
        int totalPage = (Integer.parseInt(bodyObj.getString("totalRecords")) / 10) + 1 ;
        String newProduct = "";
        for (int i = 0; i < totalPage; i++) {
            Map params1 = new HashMap();
//			params1.put("body", "{districtId='', labelId='01', cityNo='10', longitude='116.456522', signOfOrder='1', regionId='', dimension='39.93138', merTypeId2=''}");
//			params1.put("syshead", "{chnlUserId='17A8AF7157CD46FBAC97188626CA08A0', trans_code='SI_PRD0010', sessionId='null', chnlId='01', pageIndex=" + (i + 1) + ", pageSize=10}");
            params1.put("p1", "35");
            params1.put("body", "{\"cityNo\":\"10\",\"regionId\":\"\",\"longitude\":\"116.4505579326416\",\"labelId\":\"01\",\"dimension\":\"39.93005504289196\",\"merTypeId2\":\"\",\"signOfOrder\":\"1\",\"districtId\":\"\"}");
            params1.put("p6", "478931494");
            params1.put("p2", "68281119-1AB4-4D63-A54C-B9F499902DF3");
            params1.put("p7", "C7C5BC31E5544437BE1D43CF7F735627");
            params1.put("p3", "22FCB3CBBC534C61B4775AD4740DB4E7f");
            params1.put("p8", "10B9D155-E63B-4ABC-8956-769CC0D0F561");
            params1.put("p4", "A83D0972-344A-4724-974B-9F059BA93BC1");
            params1.put("p9", "7a33ae01d478482c81f9003277f7c90e");
            params1.put("p0", "i");
            params1.put("p10", "BE17D154-DD6A-4FB9-975D-00B601AD0D3E");
            params1.put("p5", "17A8AF7157CD46FBAC97188626CA08A0");
            params1.put("syshead", "{\"pageSize\":10,\"trans_code\":\"SI_PRD0010\",\"chn1_id\":\"01\",\"sessionId\":\"7a33ae01d478482c81f9003277f7c90e\",\"session_id\":\"123124123\",\"user_id\":\"17A8AF7157CD46FBAC97188626CA08A0\",\"pageIndex\":" + (i + 1) + "}");
            String pageResult = HttpUtils4Black.postUrl4ZSYH(productUrl, params1);
            JSONObject obj2 = JSONObject.parseObject(pageResult);
            JSONObject bodyObj2 = (JSONObject) obj2.get("body");
            JSONArray rows = bodyObj2.getJSONArray("rows");
            if (rows != null) {
                for (int j = 0; j < rows.size(); j++) {
                    JSONObject obj3 = rows.getJSONObject(j);
                    Product1 product = new Product1();
                    product.setProductName(obj3.getString("productName"));
                    product.setProductPicUrl(obj3.getString("productPicUrl"));
                    product.setProductNo(obj3.getString("productNo"));
                    product.setValidityPerBegin(obj3.getString("validityPerBegin"));
                    product.setValidityPerEnd(obj3.getString("validityPerEnd"));
                    product.setBtnStatus(obj3.getString("btnStatus"));
                    product.setBtnText(obj3.getString("btnText"));
                    product.setIsRemained("0");
                    productList.add(product);
                    this.productService.updateProduct1(product);
//					//到货提醒
                    if ((this.productService.findProductByNo1(obj3.getString("productNo")) != null)
                            && (this.productService.findProductByNo1(obj3.getString("productNo")).getIsRemained().equals("1"))
                            && obj3.getString("btnText").equals("立即购买")) {
                        newProduct = newProduct + "<img src='" + obj3.getString("productPicUrl") + "'>" + "</br>";
                        newProduct = newProduct + obj3.getString("productName") + " 库存：" + obj3.getString("btnText") + "</br>";
                    }
                    //新品上市
                    if ((!this.productService.isExistProductByProductNo1(obj3.getString("productNo")))
                            || (!this.productService.isExistProductByName1(obj3.getString("productName")))) {
                        this.productService.saveProduct(product);
                        newProduct = newProduct + "<img src='" + obj3.getString("productPicUrl") + "'>" + "</br>";
                        newProduct = newProduct + obj3.getString("productName")
                                + " 库存:" + obj3.getString("btnText")
                                + " 开售时间:" + obj3.getString("validityPerBegin")
                                + "</br>";
                    }
                }
            }
        }
        if (!newProduct.equals(""))
            try {
                MailUtil.sendMail("新品上市Nine", newProduct);
            } catch (Exception e) {
                e.printStackTrace();
            }
        productService.removePastProducts1();
        logger.info("nine" + "执行完毕");
    }

    @Scheduled(fixedRate = 60000)
    public void getProductList2() {
        Vector productList = new Vector();
        String productUrl = API_URL.ZSYH_ADDRESS1 + API_URL.ZSYH.PRODUCT_9POINT_LIST_URL;
        Map params = new HashMap();
        params.put("cityNo", "10");
        params.put("pageIndex", "1");
        params.put("couponType", "Jifentao");
        String result = HttpUtils4Black.postUrl4ZSYH(productUrl
                + API_URL.userArray[0][1], params);
        JSONObject obj = JSONObject.parseObject(result);
        int totalPage = Integer.parseInt(obj.getString("totalPages"));
        String newProduct = "";
        for (int i = 0; i < totalPage; i++) {
            Map params1 = new HashMap();
            params1.put("cityNo", "10");
            params1.put("pageIndex", i + 1);
            params1.put("couponType", "Jifentao");
            String pageResult = HttpUtils4Black.postUrl4ZSYH(productUrl
                    + API_URL.userArray[0][1], params1);
            JSONObject obj2 = JSONObject.parseObject(pageResult);
            JSONArray coupons = obj2.getJSONArray("coupons");
            if (coupons != null) {
                for (int j = 0; j < coupons.size(); j++) {
                    JSONObject obj3 = coupons.getJSONObject(j);
                    Product2 product = new Product2();
                    product.setName(obj3.getString("name"));
                    product.setPicUrl(obj3.getString("picUrl"));
                    product.setProductNo(obj3.getString("productNo"));
                    product.setSaleBeginTime(obj3.getString("saleBeginTime"));
                    product.setSaleEndTime(obj3.getString("saleEndTime"));
                    product.setShowStatus(obj3.getString("showStatus"));
                    product.setStock(obj3.getString("stock"));
                    product.setType("Jifentao");
                    product.setIsRemained("0");
                    productList.add(product);

                    this.productService.updateProduct2(product);

                    if ((this.productService.findProductByNo2(obj3.getString("productNo")) != null)
                            && (this.productService.findProductByNo2(obj3.getString("productNo")).getIsRemained().equals("1"))
                            && (Integer.parseInt(obj3.getString("stock")) > 0)) {
                        newProduct = newProduct + "<img src='" + obj3.getString("picUrl") + "'>" + "</br>";
                        newProduct = newProduct + obj3.getString("name") + " 库存：" + obj3.getString("stock") + "</br>";
                        //库存有时自动抢
                        String getMsg = "";
                        for (int k = 0; k < API_URL.userArray.length; k++) {
                            String userId = API_URL.userArray[k][2];
                            params.put("quantity", "1");
                            params.put("userId", userId);
                            params.put("productId", obj3.getString("productNo"));
                            params.put("orderPoint", "9");
                            params.put("orderCardType", "4");
                            HashMap localHashMap = new HashMap();
                            localHashMap.put("orderPoint", "9");
                            localHashMap.put("orderCardType", "4");
                            localHashMap.put("quantity", "1");
                            localHashMap.put("productId", obj3.getString("productNo"));
                            localHashMap.put("userId", userId);
                            String str1 = ValidateUtils.a(localHashMap, "asc");
                            String mac = ValidateUtils.getMd5UpperCase(str1 + "0102030405060708");
                            params.put("mac", mac);
                            String orderUrl = API_URL.ZSYH_ADDRESS1 + API_URL.ZSYH.CREATE_ORDER_URL;
                            String getResult = HttpUtils4Black.postUrl4ZSYH(orderUrl, params);
                            if (!getResult.contains("尊敬的客户，您的操作过于频繁，请休息片刻")) {
                                getMsg += (API_URL.userArray[k][0] + "---" + getResult) + "</br>";
                            }
                        }
                        newProduct += getMsg;
                    }

                    if ((!this.productService.isExistProductByProductNo2(obj3
                            .getString("productNo")))
                            || (!this.productService.isExistProductByName2(obj3
                            .getString("name")))) {
                        this.productService.saveProduct(product);
                        newProduct = newProduct + "<img src='" + obj3.getString("picUrl") + "'>" + "</br>";
                        newProduct = newProduct + obj3.getString("name")
                                + " 库存:" + obj3.getString("stock")
                                + " 开售时间:" + obj3.getString("saleBeginTime")
                                + "</br>";
                    }
                }
            }
        }
        if (!newProduct.equals(""))
            try {
                MailUtil.sendMail("新品上市JiFentao", newProduct);
            } catch (Exception e) {
                e.printStackTrace();
            }
        productService.removePastProducts2();
        logger.info("jifentao" + "执行完毕");
    }

}